package com.mycjj.android.activity;

/**
 * 车圈 - 主题详情 BY baiyuxiong @linewin.cc
 */
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mycjj.android.ProjectDataManage;
import com.mycjj.android.R;
import com.mycjj.android.adapter.CarNetworkCommentAdapter;
import com.mycjj.android.bean.CarNetworkCommentBaseBean;
import com.mycjj.android.bean.CarNetworkCommentBean;
import com.mycjj.android.bean.CarNetworkThemeDetailBaseBean;
import com.mycjj.android.bean.CarNetworkThemeDetailBean;
import com.mycjj.android.http.ProjectHttpRequestImpl;
import com.mycjj.android.http.ProjectHttpRequestInterface;
import com.mycjj.android.pullrefresh.PullToRefreshBase;
import com.mycjj.android.pullrefresh.PullToRefreshBase.Mode;
import com.mycjj.android.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.mycjj.android.pullrefresh.PullToRefreshBase.OnRefreshListener2;
import com.mycjj.android.pullrefresh.PullToRefreshListView;
import com.mycjj.android.util.Preferences;
import com.mycjj.android.util.Utils;

public class CarNetworkThemeDetailActivity extends BaseActivity {

	private PullToRefreshListView carnetwork_theme_comment_list;

	private String theme_id;

	private ImageView iv_pic;
	private TextView tv_name, tv_carnetwork, tv_time, tv_title, tv_top,
			tv_good, tv_recommend, tv_share, tv_comment, tv_like,tv_reply;
	private EditText et_content;
	private WebView wv_content;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_network_theme_detail);
		mPopView = getLayoutInflater().inflate(R.layout.pop_network_reply_view,
				null);

		Intent intent = this.getIntent();
		this.theme_id = intent.getStringExtra("id");
		if (Utils.isEmpty(this.theme_id)) {
			this.finish();
		}
		request = new ProjectHttpRequestImpl(
				CarNetworkThemeDetailActivity.this, true);
		
		init();
	}

	private void init() {
		initHeader();
		initData(0);
	}

	private ImageView mHeaderLeftImageview;
	private Button mHeaderRightButton;
	private TextView mHeaderTitleTextView;

	private void initHeader() {
		mHeaderLeftImageview = (ImageView) findViewById(R.id.header_left_button);
		mHeaderLeftImageview.setImageResource(R.drawable.back_selector);
		mHeaderRightButton = (Button) findViewById(R.id.header_right_button);
		mHeaderTitleTextView = (TextView) findViewById(R.id.header_title_textview);
		mHeaderTitleTextView.setText("话题详情");
		mHeaderLeftImageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				CarNetworkThemeDetailActivity.this.finish();
			}
		});
		mHeaderRightButton.setVisibility(View.GONE);

		carnetwork_theme_comment_list = (PullToRefreshListView) findViewById(R.id.carnetwork_theme_comment_list);

		carnetwork_theme_comment_list.setMode(Mode.BOTH);
		carnetwork_theme_comment_list
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						Toast.makeText(CarNetworkThemeDetailActivity.this,
								"下拉刷新", Toast.LENGTH_LONG).show();
						initData(0);
					}

					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						if (has_next_page) {// 有第二页数据
							index++;
							initData(index);
						} else {
							Toast.makeText(CarNetworkThemeDetailActivity.this,
									"没有更多的数据需要显示!", Toast.LENGTH_LONG).show();
							carnetwork_theme_comment_list.onRefreshComplete();
						}
					}

				});
		carnetwork_theme_comment_list
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						// 请求数据
						carnetwork_theme_comment_list.onRefreshComplete();// 归原来
					}
				});

		iv_pic = (ImageView) findViewById(R.id.iv_pic);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_carnetwork = (TextView) findViewById(R.id.tv_carnetwork);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_top = (TextView) findViewById(R.id.tv_top);
		tv_good = (TextView) findViewById(R.id.tv_good);
		tv_recommend = (TextView) findViewById(R.id.tv_recommend);
		wv_content = (WebView) findViewById(R.id.wv_content);
		tv_share = (TextView) findViewById(R.id.tv_share);
		tv_comment = (TextView) findViewById(R.id.tv_comment);
		tv_like = (TextView) findViewById(R.id.tv_like);
		
		et_content =  (EditText) mPopView.findViewById(R.id.et_content);
		tv_reply =  (TextView) mPopView.findViewById(R.id.tv_reply);

		iv_pic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CarNetworkThemeDetailActivity.this,
						CarNetworkFriendDetailActivity.class);
				intent.putExtra("id", carNetworkThemeDetailBean.getAuthor_id());
				startActivity(intent);
			}
		});
		tv_name.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(CarNetworkThemeDetailActivity.this,
						CarNetworkFriendDetailActivity.class);
				intent.putExtra("id", carNetworkThemeDetailBean.getAuthor_id());
				startActivity(intent);
			}
		});
		
		tv_share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		
		tv_comment.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
		        showPopWindow(-1);
				InputMethodManager inputMethodManager=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}
		});
		tv_reply.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = et_content.getText().toString();
				if(Utils.isEmpty(content))
				{
					Toast.makeText(CarNetworkThemeDetailActivity.this, "请输入回复内容", Toast.LENGTH_LONG).show();
					return;
				}
				reply(CarNetworkThemeDetailActivity.this.theme_id,et_content.getTag().toString(),content);
			}
		});
		
		tv_like.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				like(CarNetworkThemeDetailActivity.this.theme_id);
			}
		});
	}

	private CarNetworkThemeDetailBean carNetworkThemeDetailBean;
	List<CarNetworkCommentBean> themecommentList;
	private CarNetworkCommentAdapter themecommentadapter;
	private boolean has_next_page;
	private int index = 0;
	private int limit = 8;

	private void initData(int index) {
		themecommentadapter = new CarNetworkCommentAdapter(
				CarNetworkThemeDetailActivity.this);

		// 车圈详情
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		String storeid = Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "storeId", "");
		params.put("store_id", storeid);
		params.put("theme_id", this.theme_id);
		params.put("token", Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "user_token", ""));
		params.put("offset", String.valueOf(limit * index));
		params.put("limit", String.valueOf(limit));
		request.requestGetThemeWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						CarNetworkThemeDetailBaseBean activityBean = ProjectDataManage
								.getInstance()
								.getCarNetworkThemeDetailBaseBean();
						Log.d("CarNetworkThemeDetailBean",
								(null == activityBean) ? "CarNetworkThemeDetailBean is null"
										: "activityBean code"
												+ activityBean.getCode());
						if ((null != activityBean)
								&& (null != activityBean.getData())) {
							carNetworkThemeDetailBean = activityBean.getData();

							imageLoader.displayImage(carNetworkThemeDetailBean
									.getAuthor_avatar(), iv_pic);
							tv_name.setText(carNetworkThemeDetailBean
									.getAuthor_name());
							tv_carnetwork.setText(carNetworkThemeDetailBean
									.getCircle_name());
							tv_time.setText(carNetworkThemeDetailBean.getTime());
							tv_title.setText(carNetworkThemeDetailBean
									.getTitle());
							mHeaderTitleTextView
									.setText(carNetworkThemeDetailBean
											.getCircle_name());

							if (carNetworkThemeDetailBean.getIs_stick() == "1") {
								tv_top.setVisibility(View.VISIBLE);
							} else if (carNetworkThemeDetailBean.getIs_digest() == "1") {
								tv_good.setVisibility(View.VISIBLE);
							} else if (carNetworkThemeDetailBean
									.getIs_recommend() == "1") {
								tv_recommend.setVisibility(View.VISIBLE);
							}
							wv_content.loadDataWithBaseURL("",
									carNetworkThemeDetailBean.getContent(),
									"text/html", "UTF-8", "");
							tv_share.setText(carNetworkThemeDetailBean
									.getSharecount());
							tv_comment.setText(carNetworkThemeDetailBean
									.getCommentcount());
							tv_like.setText(carNetworkThemeDetailBean
									.getLikecount());
						}
					}

				});

		// 评论列表
		request.requestGetsCommentWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						CarNetworkCommentBaseBean activityBean = ProjectDataManage
								.getInstance().getCarNetworkCommentBaseBean();
						Log.d("CarNetworkCommentBaseBean",
								(null == activityBean) ? "CarNetworkCommentBaseBean is null"
										: "activityBean code"
												+ activityBean.getCode());
						if ((null != activityBean)
								&& (null != activityBean.getData())) {
							themecommentList = activityBean.getData().getList();
							themecommentadapter.setList(themecommentList);

							has_next_page = activityBean.getData()
									.isHas_next_page();
						}
					}

				});

		carnetwork_theme_comment_list.setAdapter(themecommentadapter);
	}

	private PopupWindow mPopupWindow;
	private View mPopView;

	public void showPopWindow(int position) {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow = new PopupWindow(mPopView, LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			//popupwindow弹出时的动画		popWindow.setAnimationStyle(R.style.popupWindowAnimation);
			// 使其聚集 ，要想监听菜单里控件的事件就必须要调用此方法
			mPopupWindow.setFocusable(true);
			mPopupWindow.setOutsideTouchable(true);
			// 设置背景，这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable());	
			//软键盘不会挡着popupwindow
			mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
			//设置菜单显示的位置
			mPopupWindow.showAtLocation(mPopView, Gravity.BOTTOM, 0, 0);
			
			if(position >= 0)
			{
				et_content.setHint("回复"+(position+1)+"楼");
				et_content.setTag(themecommentList.get(position).getReply_id());
			}
			else
			{
				et_content.setHint("回复楼主");
				et_content.setTag("0");
			}
		}
	}
	
	private void reply(String theme_id,String replyid,String content)
	{
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		String storeid = Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "storeId", "");
		params.put("store_id", storeid);
		params.put("theme_id", theme_id);
		params.put("reply_id", replyid);
		params.put("content", content);
		params.put("token", Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "user_token", ""));
		
		request.requestCommentWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						Toast.makeText(CarNetworkThemeDetailActivity.this,
								"回复成功", Toast.LENGTH_LONG).show();
						if (mPopupWindow != null && mPopupWindow.isShowing()) {
							mPopupWindow.dismiss();
							InputMethodManager inputMethodManager=(InputMethodManager) CarNetworkThemeDetailActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
					        inputMethodManager.hideSoftInputFromWindow(CarNetworkThemeDetailActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
						}
						initData(0);
					}
				});
	}
	
	private void like(String theme_id)
	{
		RequestParams params = new RequestParams();
		params.put("client_id", ProjectHttpRequestInterface.client_id_key);
		String storeid = Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "storeId", "");
		params.put("store_id", storeid);
		params.put("theme_id", this.theme_id);
		params.put("token", Preferences.getSharedPreferences(
				CarNetworkThemeDetailActivity.this, "user_token", ""));
		
		request.requestLikeWithDoneHandler("", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						Toast.makeText(CarNetworkThemeDetailActivity.this,
								"成功", Toast.LENGTH_LONG).show();
						tv_like.setClickable(false);
						tv_like.setText(Integer.parseInt(tv_like.getText().toString())+1);
					}
				});
	}
}
